package appx.craft.droid.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Base64;

public class UtilityHelper {

	private static final String TAG = UtilityHelper.class.getCanonicalName();
	
	public static void verifyImagePath(){
		File dir = new File(Constance.IMAGE_DIR);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		dir = null;
		
	}
	
	/**
	 * 
	 * @param request_code
	 * @param typeIntent
	 *            like image/* , video/*
	 */
	public static void openCustomIntent(final Context mContext,
			int request_code, String typeIntent) {

		Intent captureIntent = null;
		// Camera.
		final List<Intent> cameraIntents = new ArrayList<Intent>();
		if (typeIntent.equalsIgnoreCase("image/*")) {

			Log.d(TAG, "[ typeIntent ] " + typeIntent);
			captureIntent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			verifyImagePath();
			Log.d(TAG, "[Storege.verifyImagePath()]");
			File output = new File(Constance.IMAGE_DIR, "camerascript.png");
			Log.d(TAG, "[output File Path]" + output.getAbsolutePath());
			if (output.exists()) {
				output.delete();
			}
			captureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(output));

		} else if (typeIntent.equalsIgnoreCase("video/*")) {
			captureIntent = new Intent(
					android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
		}

		final PackageManager packageManager = mContext.getPackageManager();
		final List<ResolveInfo> listCam = packageManager.queryIntentActivities(
				captureIntent, 0);

		for (ResolveInfo res : listCam) {

			final String packageName = res.activityInfo.packageName;
			final Intent intent = new Intent(captureIntent);
			intent.setComponent(new ComponentName(res.activityInfo.packageName,
					res.activityInfo.name));
			intent.setPackage(packageName);
			cameraIntents.add(intent);
		}

		// Filesystem.
		final Intent galleryIntent = new Intent();
		galleryIntent.setType(typeIntent);
		galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

		final Intent chooserIntent = Intent.createChooser(galleryIntent,
				"Select Source");
		chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
				cameraIntents.toArray(new Parcelable[] {}));
		((Activity) mContext).startActivityForResult(chooserIntent,
				request_code);
	}

	/**
	 * Get Absulote Path from URI
	 * 
	 * @param contentUri
	 * @return
	 */
	public static String getRealPathFromURI(final Context mContext,
			Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = ((Activity) mContext).managedQuery(contentUri, proj,
				null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public static String imageEncodeTobase64(Bitmap image) {
		Bitmap immagex = image;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		immagex.compress(Bitmap.CompressFormat.JPEG, 40, baos);
		byte[] b = baos.toByteArray();
		String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
		Log.d(TAG, imageEncoded);
		return imageEncoded;
	}

	public static boolean isOnline(Context mContext) {
		try {

			ConnectivityManager connMgr = (ConnectivityManager) mContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isConnected()) {
				// fetch data
				Log.d(TAG,
						"[ %%%%%%%%%%% YOUR NETWORK_PROVIDER IS AVAILABLE  ]");

				return true;
			} else {
				// display error
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static String extractTimefromDate(String fullDate) {
		String resultTime = "";
		try {

			SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy hh:mm a");
			Date mDate = sdf.parse(fullDate);
			SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a");
			resultTime = String.valueOf(sdf2.format(mDate));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultTime;

	}

	public static String extractDateFromTimeStemp(String fullDate) {

		String resultDate = "";
		try {

			SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy hh:mm a");
			Date mDate = sdf.parse(fullDate);
			SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMM, yyyy");
			resultDate = String.valueOf(sdf2.format(mDate));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultDate;

	}

		public static String extractFileName(String path) {

		if (path == null) {
			return null;
		}
		String newpath = path.replace('\\', '/');
		int start = newpath.lastIndexOf("/");
		if (start == -1) {
			start = 0;
		} else {
			start = start + 1;
		}
		String pageName = newpath.substring(start, newpath.length());

		return pageName;
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmapFromResource(String filePath, int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options); 
		
	}
	
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}
